import React from 'react';
import {
  StyleSheet,
  View,
  Image,
  Text,
  TouchableOpacity,
  ScrollView,
  Dimensions,
  RefreshControl,
} from 'react-native';
const { width , height} = Dimensions.get('window');
import { pageMyFllow } from '../../api/my'
import RecommendTea from '../../component/RecommendTea'
import Loading from '../../common/Loading'
import NavigatorBar from '../../common/NavigationBar';
import BottomBarLimit from '../../common/BottomBarLimit'
import {setSpText,setHW} from '../../component/ScreenUtil'

import BackPressComponent from '../../common/BackPressComponent';

var cacheData = {
  total:0,
  items: [],
  nextPage: 1
}
export default class MyCare extends React.Component {
  constructor(props) {
    super(props);
    this.params=this.props.navigation.state.params;
    this.state = {
      loading: true,
      dataList: [],
      dataMore: false,
      isRefreshing: false,
      deEmitter:null,
      isLoading: false
    }
    this.backPress = new BackPressComponent({ backPress: (e) => this.onBackPress(e) });
  }

  onBackPress() {
    // console.log('back', this);
    this.params && this.params.refreshPage && this.params.refreshPage();//返回上一个页面的refreshPage()
  }
  // 获取我的收藏
  componentDidMount() {
    this.backPress.componentDidMount();
    this._pageMyFllow()
  }
  componentWillUnmount(){
    this.backPress.componentWillUnmount();
    // this.state.deEmitter.remove();
  }
  // 取消关注的操作，需要最后刷新页面操作时
  reSearchData(){
    this.setState({
      dataList: [],
      loading: true,
    });
   this._pageMyFllow()
  }
  _pageMyFllow() {
    let json = {
      "PAGE": cacheData.nextPage,
      "ROWS": 10,
      "USER_ID": global.ECourseConstant.userInfo.uuid
    }
    pageMyFllow(json).then(res => {
      global.log(res, '我的关注')
      res.LIST.forEach(item => {
        item.HEADPORTRAIT = item.HEAD_PORTRAIT;//老师照片
        item.NAME = item.TEACHERNAME;//老师名字
        item.hadFellow = '1';//已关注
        item.USERID = item.USER_ID;//老师id
        item.SELFINTRODUCTION = item.SELF_INTRODUCTION//老师介绍
      });
      cacheData.items = this.state.dataList.concat(res.LIST);
      cacheData.total = res.PAGINATION.TOTAL
      var data = [...cacheData.items];
      this.setState({
        loading: false,
        dataList: data
      });
    })
  }
  render() {
    return (
      <View style={styles.MyCare}>
        <NavigatorBar title={'关注的老师'} style={styles.navigatorBar} 
        leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))} />
        <ScrollView
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this._onRefresh.bind(this)}
              tintColor="#FF8A00"
              // title="加载中..."
              titleColor="#ddd"
              colors={['#FF8A00']}
              progressBackgroundColor="#ffffff"
            />
          }
          onScroll={this._onScroll.bind(this)}
          scrollToEnd={() => { this._scrollToEnd }}
          scrollEventThrottle={20}
        >
            <RecommendTea
                TeacherList={this.state.dataList}
                reSearchData={()=>this.reSearchData()}
                {...this.props}>
            </RecommendTea>
          {this.loadMore()}
					{this.loading()}
					{this.NoData()}
        </ScrollView>
      </View>
    );
  }
  // 刷新
  _onRefresh() {
    if(this.state.dataList.length){
      cacheData = {
        items: [],
        nextPage: 1,
        total: 0
      }
      this.setState({
        dataList: [], // 推荐课程数据
        isLoading: false,
        dataMore: false,
      })
      this._pageMyFllow();
    }else{
      this.setState({
        dataMore: false,
      })
    }

  }
  hasMoreList() {
    if (this.state.dataList.length == cacheData.total && cacheData.total > 0) {
      this.setState({
        dataMore: false
      })
      return false
    }
    return true
    // 
  }
  // 加载更多数据
  _onScroll(event) {
    if (this.state.isLoading || !this.hasMoreList()) {
      return;
    }
    let y = event.nativeEvent.contentOffset.y;
    let height = event.nativeEvent.layoutMeasurement.height;
    let contentHeight = event.nativeEvent.contentSize.height;
    if (y + height >= contentHeight - 20) {
      this.setState({
        isLoading: false
      }, () => {
        cacheData.nextPage = cacheData.nextPage + 1;
        this._pageMyFllow()
      });
    }
  }
  componentWillMount() {
    cacheData = {
      items: [],
      nextPage: 1,
      total: 0
    }
    this.setState({
      dataList: [], // 推荐课程数据
      isLoading: false,
      dataMore: false,
    })
  }
  // 加载loading
  loading(){
    if(this.state.loading){
      return(
        <View style={{height:height - 70}}>
            <Loading/>
        </View>
      )
    }
  }
  // 正在加载or底部
  loadMore(){
    if(!this.state.loading&&this.state.dataList.length>10){
      if(this.state.dataMore){
        return(
          <View style={styles.loadMore}>
            <Text style={styles.loadMoreText}>正在加载中...</Text>
          </View>
        )
      }else{
        return(
          <View style={styles.loadMore}>
            <Text style={styles.loadMoreText}>已经全部加载完毕</Text>
          </View>
        )
      }
    }
  }
  // 没有数据
  NoData(){
    if(!this.state.loading&&!this.state.dataMore&&!this.state.dataList.length){
      return(
        <Text style={styles.empty}>暂无数据</Text>
      )
    }
  }
    // 渲染按钮 返回按钮
  renderLeftButton(image) {
      return <TouchableOpacity
        style={{ padding: 8 }}
        onPress={() => {
          this.params&&this.params.refreshPage();//返回上一个页面的refreshPage()
          this.props.navigation.goBack();//pop就会返回上一个页面
        }}>
        <Image style={{ width: 34, height: 34 }} source={image} />
      </TouchableOpacity>;
    }
}
const styles = StyleSheet.create({
  MyCare: {
    flex: 1,
    backgroundColor: '#F7F7F9',
  },
  empty: {
    backgroundColor: '#fff',
    textAlign: 'center',
    height: height - setHW(100),
    lineHeight:setHW(400),
    color: '#666',
    fontSize:setSpText(28),
    width: width,
  },
  loadMore: {
    flexDirection: 'row',
    justifyContent: 'center',
    height: setHW(100),
    alignItems: 'center',
  },
  loadMoreText: {
    color: '#ddd',
  }
})